/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SeleccAmigos.java
 *
 * Created on 03-nov-2011, 11:08:50
 */
package Ventanas;

import Objetos.PropiedadesIP;
import Proxies.CtrlChatWS;
import Proxies.CtrlChatWSService;
import Proxies.CtrlMovilWS;
import Proxies.CtrlMovilWSService;
import Proxies.CtrlUsuariosWS;
import Proxies.CtrlUsuariosWSService;
import Proxies.DataUsuarioArray;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.xml.namespace.QName;

/**
 *
 * @author Sebas
 */
public class SeleccAmigos extends javax.swing.JDialog {

    private String mailUsr;
    private Principal principal;

    /** Creates new form SeleccAmigos */
    public SeleccAmigos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public SeleccAmigos(java.awt.Frame parent, boolean modal, String mail, Principal princ) {
        super(parent, modal);
        initComponents();
        mailUsr = mail;
        cargarAmigos();
        principal = princ;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtable_amigos = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jtable_amigos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nick", "Correo", "Imagen"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtable_amigos);

        jLabel1.setText("SELECCIONAR AMIGO PARA INICIAR CONVERSACION");

        jButton1.setText("Seleccionar amigo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(61, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(36, 36, 36))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(183, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        String amigoChat = jtable_amigos.getValueAt(jtable_amigos.getSelectedRow(), 1).toString();

        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlChat?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(SeleccAmigos.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlChatWSService");

        CtrlChatWS chat = new CtrlChatWSService(dir, qNa).getCtrlChatWSPort();

        URL dir2 = null;
        try {
            dir2 = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(SeleccAmigos.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa2 = new QName("http://WebServices/", "CtrlUsuariosWSService");

        int iniciarConv = chat.inciarConv(mailUsr, amigoChat);
        String correo = (String) jtable_amigos.getModel().getValueAt(jtable_amigos.getSelectedRow(), 1);
        Conversacion conversa = new Conversacion(null, false, mailUsr, iniciarConv, principal);
        principal.agregarConversacion(conversa);
        conversa.setVisible(true);
        conversa.setLocationRelativeTo(null);
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SeleccAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SeleccAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SeleccAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SeleccAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                SeleccAmigos dialog = new SeleccAmigos(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtable_amigos;
    // End of variables declaration//GEN-END:variables

    private void cargarAmigos() {
        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlMovil?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(SeleccAmigos.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlMovilWSService");
        CtrlMovilWS ctrlMov = new CtrlMovilWSService(dir, qNa).getCtrlMovilWSPort();

        URL dir2 = null;
        try {
            dir2 = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(SeleccAmigos.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa2 = new QName("http://WebServices/", "CtrlUsuariosWSService");
        CtrlUsuariosWS ctrlUsr = new CtrlUsuariosWSService(dir2, qNa2).getCtrlUsuariosWSPort();

        DataUsuarioArray amis = ctrlUsr.listarDAmigos(mailUsr);
        DefaultTableModel model = (DefaultTableModel) jtable_amigos.getModel();
        model.setRowCount(0);
        if (!amis.getItem().isEmpty()) {
            Object[] fila = new Object[3];
            Iterator<Proxies.DataUsuario> itera = amis.getItem().iterator();
            Proxies.DataUsuario usr;
            while (itera.hasNext()) {
                usr = itera.next();
                boolean estaConectado = ctrlMov.isConectadoUsuario(usr.getCorreo());
                if (estaConectado) {
                    fila[0] = usr.getNick();
                    fila[1] = usr.getCorreo();
                    fila[2] = usr.getImagen();
                    model.addRow(fila);
                }
            }
        }

    }
}
